package com.liuqi.knet.remoting.transport;

import com.liuqi.knet.remoting.ChannelHandler;
import com.liuqi.knet.remoting.Codec;
import com.liuqi.knet.remoting.Endpoint;
import com.liuqi.knet.remoting.KNetConfig;
import com.liuqi.knet.remoting.RemotingException;

/**
 * @author liuqi
 * @date 2024/12/17 17:47
 **/
public abstract class AbstractEndpoint implements Endpoint {

    protected final ChannelHandler handler;

    protected final KNetConfig netConfig;

    protected final Codec codec;

    protected volatile boolean closed;

    public AbstractEndpoint(ChannelHandler handler, KNetConfig netConfig) {
        if (handler == null) {
            throw new NullPointerException("handler == null");
        }
        if (netConfig == null) {
            throw new NullPointerException("netConfig == null");
        }
        if (netConfig.getCodec() == null) {
            throw new NullPointerException("netConfig.codec == null");
        }
        this.handler = handler;
        this.netConfig = netConfig;
        this.codec = netConfig.getCodec();
    }

    @Override
    public ChannelHandler getChannelHandler() {
        if (handler instanceof ChannelHandlerDelegate) {
            return ((ChannelHandlerDelegate) handler).getHandler();
        } else {
            return handler;
        }
    }

    @Override
    public void send(Object message) throws RemotingException {
        send(message, isSent());
    }

    @Override
    public void close() {
        closed = true;
    }

    @Override
    public boolean isClosed() {
        return closed;
    }

    protected boolean isSent() {
        return netConfig.isSent();
    }

    protected int getTimeout() {
        return netConfig.getTimeout();
    }

    protected Codec getCodec() {
        return codec;
    }

    protected KNetConfig getNetConfig() {
        return netConfig;
    }
}
